package com.example.swimmingpool.service.notice;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.example.swimmingpool.SwimmingPoolThreadLocal;
import com.example.swimmingpool.entity.notice.Notice;
import com.example.swimmingpool.vo.notice.NoticeVo;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import jakarta.annotation.Resource;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NoticeService {
    @Resource
    private MongoTemplate mongoTemplate;

    public boolean insert(Notice notice){
        var userId = SwimmingPoolThreadLocal.getUserId();
        notice.setUserId(String.valueOf(userId))
         .setCreateTime(LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.NORM_DATETIME_PATTERN))
                .setSort(1L);
         return mongoTemplate.insert(notice).getId()!=null;
    }

    public List<Notice> list(){

        Query query = new Query();
        query.with(Sort.by(Sort.Direction.ASC,"sort"));

        return mongoTemplate.find(query,Notice.class);
    }

    public Boolean delete(String id){
        Query query = new Query(Criteria.where("_id").is(new ObjectId(id)));
        DeleteResult remove = mongoTemplate.remove(query, Notice.class);
        return remove.getDeletedCount()>0;

    }

    public Boolean update(NoticeVo vo){
        var id = new ObjectId(vo.getId());
        var sort = vo.getSort();
        Update update = new Update();
        update.set("sort", sort);
        Query query = new Query(Criteria.where("_id").is(id));
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Notice.class);
        return updateResult.getModifiedCount() > 0;
    }
}
